'use strict';

const path = require('path')
const Package = require('@fobiz-cli/package')
const log = require('@fobiz-cli/log')
const {exec: spawn} = require('@fobiz-cli/utils')

const SETTINGS = {
    init: '@fobiz-cli/init'
}

// 缓存文件夹名
const CACHE_DIR = 'dependencies';

async function exec() {
    let targetPath = process.env.CLI_TARGET_PATH
    let storeDir = '';
    let pkg;
    const cliHomePath = process.env.CLI_HOME_PATH
    log.verbose('targetPath', targetPath)
    log.verbose('homePath', cliHomePath)

    const cmdObj = arguments[arguments.length - 1]
    const cmdName = cmdObj.name()
    const packageName = SETTINGS[cmdName]
    const packageVersion = 'latest'
    log.verbose('init package name', packageName)

    // 没有指定init包的安装目录
    if (!targetPath) {
        // 默认安装在cliHome的缓存路径
        targetPath = path.resolve(cliHomePath, CACHE_DIR)
        storeDir = path.resolve(targetPath, 'node_modules')
        log.verbose('targetPath', targetPath)
        log.verbose('storeDir', storeDir)

        pkg = new Package({
            targetPath,
            storeDir,
            packageName,
            packageVersion
        });
        if (await pkg.exists()) {
            await pkg.update()
        } else {
            await pkg.install()
        }
    } else {
        pkg = new Package({
            targetPath,
            packageName,
            packageVersion
        });
    }

    const entryFile = pkg.getEntryFilePath()
    log.verbose('init package entry file', entryFile)
    if (entryFile) {
        try {
            const args = Array.from(arguments)
            const cmd = args[args.length - 1]
            const o = Object.create(null)
            Object.keys(cmd).forEach(key => {
                if (cmd.hasOwnProperty(key) &&
                    !key.startsWith('_') &&
                    key !== 'parent') {
                    o[key] = cmd[key]
                }
            })
            args[args.length - 1] = o;
            const code = `require('${entryFile}')(${JSON.stringify(args)})`
            // 执行init包的入口文件
            const child = spawn('node', ['-e', code], {
                cwd: process.cwd(),
                stdio: 'inherit'
            })
            child.on('error', e => {
                log.error(e.message)
                process.exit(1)
            })
            child.on('exit', e => {
                log.verbose('命令执行成功：' + e)
                process.exit(0)
            })
        } catch (e) {
            log.error(e.message)
        }
    }
}

module.exports = exec;
